<template>
    <div class="main">
        <div style="margin: 0px 0px 10px 10px; padding-top: 10px; display: flex; align-items: center">
            <i class="el-icon-edit"> BitDesk</i>
        </div>
        <div class="info">
            <div style="width: 60px; height: 60px; background: red; border-radius: 50%"></div>
            <div>
                <div style="font-weight: bold; margin-bottom: 5px">MacBook Pro</div>
                <div style="font-size: 13px; color: #999">设备代码: {{ to | identifyCode }}</div>
                <div style="font-size: 13px; color: #999">BitDesk是安全流畅的远程控制软件</div>
            </div>
            <el-button type="danger" size="mini" @click="handleClose">断开</el-button>
        </div>
    </div>
</template>

<script>
import io from 'socket.io-client'
let socket
export default {
    data() {
        return {
            from: this.$route.query.from,
            to: this.$route.query.to,
            mark: this.$route.query.mark,
            peer: null,
            dataChannel: null,
            userId: '',
            signalingState: false,
            remoteCandidates: []
        }
    },
    filters: {
        identifyCode(value) {
            if (value) {
                return value.substr(0, 3) + ' ' + value.substr(3, 3) + ' ' + value.substr(6, 3)
            }
            return value
        }
    },
    created() {
        this.userId = this.$route.query.from + '_' + this.$route.query.to + '_' + this.$route.query.mark
        socket = io.connect(window.platform.socketioUrl + '?userId=' + this.userId)
        socket.on('connect', () => {
            console.log('connected to server')
            this.signalingState = false
            this.remoteCandidates = []
            this.acceptCall()
        })
        socket.on('disconnected', () => {
            console.log('disconnected with server')
        })
        socket.on('reconnect_error', error => {
            console.log('reconnect_error with server')
        })
        socket.on('sendOffer', async data => {
            const iceConfiguration = {
                iceServers: [
                    { urls: 'stun:36.139.163.176:3478' },
                    {
                        urls: 'turn:36.139.163.176:3478',
                        username: 'authors',
                        credential: 'test110'
                    }
                ]
            }
            this.peer = new RTCPeerConnection(iceConfiguration)
            console.log('4、创建RTCPeerConnection')
            this.peer.onicecandidate = event => {
                if (event.candidate) {
                    console.log(event.candidate)
                    socket.emit('message', {
                        event: 'sendCandidateCalled',
                        candidate: event.candidate,
                        source: this.userId,
                        target: [this.to + '_' + this.from + '_' + this.mark]
                    })
                }
            }
            this.peer.onconnectionstatechange = () => {
                console.log(this.peer.connectionState)
                if (this.peer.connectionState === 'disconnected') {
                    this.peerClose()
                    window.ipcRenderer.send('closeAnswer')
                }
            }
            //第一步:创建RTCPeerConnection
            //this.peer = new RTCPeerConnection()
            this.dataChannel = this.peer.createDataChannel('dataChannel')
            //第二步"添加桌面流addStream
            const stream = await this.getScreenStream()
            console.log('5、添加桌面流addStream')
            this.peer.addStream(stream)
            this.peer.ondatachannel = event => {
                let receivedChannel = event.channel
                receivedChannel.onmessage = event => {
                    if (event.data === 'close') {
                        this.peerClose()
                        window.ipcRenderer.send('closeAnswer')
                    } else {
                        window.ipcRenderer.send('robot', JSON.parse(event.data))
                    }
                }
            }
            //第三步:setRemoteDescription(设置控制端offer SDP)
            await this.peer.setRemoteDescription(data.offer)
            console.log('6、setRemoteDescription(设置控制端offer SDP)')
            //第四步:响应连接createAnswer(得到answer SDP)
            let answer = await this.peer.createAnswer()
            console.log('7、响应连接createAnswer(得到answer SDP)')
            //第五步:setLocalDescription(设置answer SDP)
            await this.peer.setLocalDescription(answer)
            console.log('8、setLocalDescription(设置answer SDP))')
            this.signalingState = true
            console.log('11、设置addIceCandidate Numbers:' + this.remoteCandidates.length)
            this.remoteCandidates.forEach(async candidate => {
                await this.peer.addIceCandidate(candidate)
            })
            socket.emit('message', {
                event: 'sendAnswer',
                answer: answer,
                source: this.userId,
                target: [this.to + '_' + this.from + '_' + this.mark]
            })
        })
        socket.on('sendCandidateCaller', async data => {
            if (this.signalingState) {
                console.log('11、设置addIceCandidate')
                await this.peer.addIceCandidate(data.candidate)
            } else {
                this.remoteCandidates.push(data.candidate)
            }
        })
    },
    methods: {
        async acceptCall(data) {
            const size = await window.ipcRenderer.invoke('getSize')
            socket.emit('message', {
                event: 'acceptCall',
                width: size.width,
                height: size.height,
                source: this.userId,
                target: [this.to + '_' + this.from + '_' + this.mark]
            })
        },
        async getScreenStream() {
            const sources = await window.ipcRenderer.invoke('getScreenStream')
            const stream = await navigator.mediaDevices.getUserMedia({
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: sources[0].id
                        // width: 2880,
                        // height: 1800,
                        // minWidth: 2880,
                        // maxWidth: 2880,
                        // minHeight: 1800,
                        // maxHeight: 1800,
                        // minFrameRate: 30,
                        // maxFrameRate: 60,
                        // devicePixelRatio: 2
                    }
                }
            })
            return stream
        },
        peerClose() {
            if (this.peer) {
                this.peer.close()
            }
        },
        handleClose() {
            if (this.peer) {
                this.dataChannel.send('close')
                this.peer.close()
            }
            window.ipcRenderer.send('closeAnswer')
        }
    }
}
</script>

<style scoped>
.main {
    height: 120px;
}
.info {
    display: flex;
    justify-content: space-around;
    align-items: center;
}
</style>
